package org.laobai.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.codingapi.txlcn.tc.annotation.TccTransaction;
import com.codingapi.txlcn.tracing.TracingContext;
import org.laobai.common.asserts.Asserts;
import org.laobai.common.metas.OrderStatus;
import org.laobai.common.struct.PageResult;
import org.laobai.goods.cilent.GoodsClient;
import org.laobai.order.entity.Order;
import org.laobai.order.entity.OrderItem;
import org.laobai.order.mapper.OrderMapper;
import org.laobai.order.service.OrderItemService;
import org.laobai.order.service.OrderService;
import org.laobai.order.util.StringUtils;
import org.laobai.order.vo.SearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiusan
 * @since 2020-11-24
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private OrderItemService orderItemService;

    @Override
    public PageResult<Order> page(Integer currPage, Integer pageSize, SearchVO vo) {
        // 分页
        Page<Order> orderPage = new Page<>(currPage, pageSize);

        // 条件查询
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        if (Objects.nonNull(vo)) {
            String keyWord = vo.getKeyWord();
            if (StringUtils.isNotEmpty(keyWord)) {
                wrapper.like("name", keyWord);
            }
        }
        orderPage = page(orderPage, wrapper);
        return PageResult.of(orderPage.getRecords(), orderPage.getTotal());
    }

    @Override
    @Transactional
    //-->分布式事务
    @LcnTransaction
    public boolean saveOrder(Order order) {
        // 初始化订单
        initOrder(order);
        // 处理订单子项
        List<OrderItem> items = order.getItems();
        String id = order.getId();
        // 设置订单ID
        for (OrderItem item : items) {
            item.setOrderId(id);
            // 扣减库存
            goodsClient.updateGoodsNum(item.getGoodsId(),0-item.getNum());
        }

        // 保存订单
        save(order);
        // 保存订单子项
        orderItemService.saveBatch(items);
        System.out.println(TracingContext.tracing().groupId());

        if(order.getTotalPrice().doubleValue()>4000){
            throw new RuntimeException("报错啦");
        }
        return true;
    }

    private void initOrder(Order order) {

        order.setId(UUID.randomUUID().toString().replace("-",""));
        // 下单用户 临时写死
        // TODO
        order.setUserId(1L);
        order.setCreateTime(new Date());
        order.setOrderStatus(OrderStatus.WAIT_PAY.ordinal());
        //订单逻辑删除
        order.setStatus(0);
    }

    @Override
    public boolean updateOrder(Order order) {
        return updateById(order);
    }

    @Override
    public boolean delById(Long id) {
        return removeById(id);
    }

    @Override
    public boolean delByIds(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    public Order getOrderDetails(String id) {
        Order order = getById(id);
        // 断言
        Asserts.isNotNull(order,"订单不存在");
        // 根据订单ID 查询订单子项
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();

        wrapper.eq("order_id",id);

        List<OrderItem> list = orderItemService.list(wrapper);

        order.setItems(list);

        return order;
    }
}
